# -*- coding: utf-8 -*-
import datetime
import time
import countour_predict_value as cpv
import schedule
import GetMysql
import means
from MysqlHelp import DB

#result参数说明 result[2]纬度  result[1]经度 result[4]定位级别
def five_minutes(count):
    size = 60
    span = -4
    start(size,span,count)
    

def start(size,span,count):
    end_time = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    start_time = str((datetime.datetime.now()+datetime.timedelta( hours= span)).strftime("%Y-%m-%d %H:%M:%S"))
    #查询record表中在五分钟内新增的频率信息
    frequencyList = GetMysql.get_frequency_fiveMinutes(size)
    whitelist = ['87.9','88.7','89.9','90.9','91.4','93.4','94.0','94.7','95.9','97.2','97.7','98.1','99.0','100.1',
    '100.3','100.9','101.7','102.5','102.7','103.7','105.1','105.7','106.5','106.7','107.2','107.7','96.2','95.5']
    # frequencyList = ['92.4']
    
    print(frequencyList)
    #遍历frequencyList 获取单个频率的值
    for frequency in frequencyList:
        
        print('这是执行的第'+str(count)+'周期')
        str_frequency = frequency['frequency']
        if str_frequency in whitelist:
            if count % 3 == 0:
                print(str_frequency+'是白名单中的频率，是第9个周期，计算位置！')
                count_data(end_time,start_time,str_frequency,size)
            else:
                print(str_frequency+'是白名单中的频率，但不是第9个周期')
                continue

        else:
            print(str_frequency+'不在白名单内，直接计算位置！')
            count_data(end_time,start_time,str_frequency,size)

    

def count_data(end_time,start_time,str_frequency,size):
    # str_frequency = frequency 
    # print(str_frequency)
    #根据频率查询存储过程中的deviceids
    # str_frequency = str(list(frequency.values())).replace('[','').replace(']','').replace('\'','')
    # deviceidList =GetMysql.get_deviceid(str_frequency)
    res =GetMysql.get_deviceids(str_frequency)
    # res = [['123456780001734', '123456780001635'], ['123456780002665', '123456780001733']]
    # print(res,"存储过程中返回的数据！！")

    for deviceid in res:
        print('deviceid',deviceid)
        devicelistone = ','.join(deviceid)
        # print(devicelist)
        # 查询fmlocation中的的频率信息
        #定位算法计算结果
        # result = cpv.pred_location(str_frequency, start_time, end_time,deviceidList )
        result = cpv.pred_location(str_frequency, start_time, end_time,devicelistone)
        print(result)
        if result is not None and len(result) > 0:
            #执行下一步计算
            run_next(end_time,size,str_frequency,result,devicelistone)
        else :
            print("定位算法未计算出坐标，重新测算！")
            # result_rssi = means.get_device_addr(str_frequency,deviceid)
            # res =GetMysql.get_deviceids(str_frequency)
            # print(res)
            # pointlist = []
            # datalist = []
            # for i in deviceid:
            #     result = GetMysql.get_point(i)
            #     pointlist.append(result)
            # res_point = means.center_geolocation(pointlist)
            # datalist.append(str_frequency)
            # datalist.append(res_point[0])
            # datalist.append(res_point[1])
            # datalist.append(devicelist)
            # datalist.append(6)
            # run_next(end_time,size,str_frequency,datalist,devicelist)
            # ——————————————————————————————————————————————————————————————
            pointlist = []
            datalist = []
            # resultlist = [] 
            for devicelist in res: 
                # print('打印num的值',num)
                # str_devicelist = ','.join(device)
                for i in devicelist:
                    # print('打印i的值',i)
                    result_point = GetMysql.get_point(i)
                    pointlist.append(result_point)
                    # print(result_point)

                res_point = means.center_geolocation(pointlist)
                # print('打印res_point的值',res_point)
                # datalist.append(frequency)
                # datalist.append(res_point[0])
                # datalist.append(res_point[1])
                # datalist.append(i)
                # datalist.append(6)
                datalist = [str_frequency,res_point[0],res_point[1],devicelistone,6]
                print('-----------------',datalist)
                #执行下一步计算
                run_next(end_time,size,str_frequency,datalist,devicelistone)
                # resultlist.append(datalist)
                # print('++++++++++++++++++++=',resultlist)

def run_next(end_time,size,str_frequency,result,deviceidList):
    # 获取位置信息
    result_addr = list(means.jsonFormatAdd(str(result[2]),str(result[1])))
    address = ''.join(result_addr)
    print("result_address+++++++++++++++++++++++++++++++++",address)
    #查询frequency是否存在radiolist表中
    res_radiolist = GetMysql.sel_radiolist(str_frequency)
    #设置fmcoding初始值
    fmcoding = (str_frequency+"_"+str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")).replace('-','').replace(':','').replace(' ',''))

    #判断经纬度是否是在上海周边范围内
    #result[2]纬度  result[1]经度
    nowtime = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    if result[2] is not None and 29.0 <= result[2] <= 33.0:
        if result[1] is not None and 119.0 <= result[1] <= 123.0:

            print("打印radiolist中是否存在该频率",res_radiolist)
            #判断该frequency是否存在radiolist表中
            if res_radiolist is not None and len(res_radiolist) > 0:
                #存在，判断经纬度坐标是否在规定的范围内

                run_second(nowtime,str_frequency,result,deviceidList,address,size,fmcoding,res_radiolist)


            else:

                nowtime = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                #新增数据
                print("新发现的发射源，新增数据创建新的FmCoding")
                GetMysql.ins_fmlocation(nowtime,size,str_frequency,result[1],result[2],fmcoding,deviceidList,str(result[4]),address)

        else:
            print("坐标超出范围，不保存数据！")
    else:
        print("坐标超出范围，不保存数据！")

def run_second(nowtime,str_frequency,result,deviceidList,address,size,fmcoding,res_radiolist):
    #范围内，新增一条数据，fmcoding取原来的；范围外新增，fmcoding新建
    #1.计算出定位坐标和之前坐标点距离
    #2.判断距离是否在之前所有坐标的20Km外

    #edit用来计数范围超出之前坐标20km的次数
    edit = 0
    for data in res_radiolist:

        distance = means.error_range(data[3],data[2],result[2],result[1])
        print("误差范围为："+str(distance))
        if  distance < 20000.0:
            print("误差范围内新增数据,不生成新的FMcoding")
            #在20km内，应新增数据，fmcoding取原来的
            GetMysql.ins_fmlocation(nowtime,size,str_frequency,result[1],result[2],data[1],deviceidList,str(result[4]),address)
            break
        else:
            #计算的坐标在之前坐标距离20km外，edit+1
            edit += 1
    #当范围超出20km的次数等于查出数组的长度，说明当前计算的坐标在所有已知坐标的20km外
    if edit == len(res_radiolist) and edit > 0:
        print("所有数据在误差范围外新增数据,生成新的FMcoding")
        #在20km外，新增数据，fmcoding新建
        GetMysql.ins_fmlocation(nowtime,size,str_frequency,result[1],result[2],fmcoding,deviceidList,str(result[4]),address)




if __name__ == '__main__':
    n = 1
    while True:
        print('循环的周期数为：',n)
        five_minutes(n)
        time.sleep(3600)
        n = n+1
     
    

    # schedule.every(5).seconds.do(job1)
    # schedule.every(5).seconds.do(five_minutes)
    # schedule.every(3600).seconds.do(thirty_minutes)
    # schedule.every(86400).seconds.do(one_day)
    # schedule.every(300).seconds.do(synchronous_mql.synchronous_data)

    # while True:
    #     schedule.run_pending()
    #     time.sleep(2)